//
//  HMXMPPRoomManager.m
//  HMWeChat
//
//  Created by apple on 2017/5/13.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMXMPPRoomManager.h"

static HMXMPPRoomManager *_instance;

@interface HMXMPPRoomManager ()<XMPPRoomDelegate>


@end

@implementation HMXMPPRoomManager


+ (instancetype)sharedManager{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [HMXMPPRoomManager new];
        
    });
    return _instance;
}

- (void)createOrJoinRoomWithRoomJID:(XMPPJID *)roomJID andNickname:(NSString *)nickname{

    //从缓存中取出数据  value: room  key: roomJID
    XMPPRoom *room = self.roomCache[roomJID.user];
    
    //判断是否存在
    if (room == nil) {
        //没有,创建并且添加到缓存中
        //创建房间模块
        room = [[XMPPRoom alloc] initWithRoomStorage:[XMPPRoomCoreDataStorage sharedInstance] jid:roomJID dispatchQueue:dispatch_get_main_queue()];
        //激活模块
        [room activate:[HMXMPPManager sharedManager].xmppStream];
        //添加到缓存中
        [self.roomCache setValue:room forKey:roomJID.user];
        
        //设置代理
        [room addDelegate: self delegateQueue:dispatch_get_main_queue()];
    }
    
    //有缓存,直接使用

    //创建/加入房间
    [room joinRoomUsingNickname:nickname history:nil];
}


#pragma mark - XMPPRoomDelegate

//创建房间后调用
- (void)xmppRoomDidCreate:(XMPPRoom *)sender{

    NSLog(@"房间创建");
    //查询配置模板
    [sender fetchConfigurationForm];

}

- (void)xmppRoom:(XMPPRoom *)sender didFetchConfigurationForm:(DDXMLElement *)configForm{

    NSLog(@"获取到配置模板: %@", configForm);
    
    //配置房间 传递nil会使用默认配置
    [sender configureRoomUsingOptions:nil];
}

#pragma mark - 懒加载

- (NSMutableDictionary *)roomCache{
    if (_roomCache == nil) {
        _roomCache = [[NSMutableDictionary alloc] init];
    }
    return _roomCache;
}

@end
